import 'dart:async';
import 'dart:developer';

import 'package:get/get.dart';
import 'package:im_base/im_base.dart';
import 'package:im_base/public/global/global.dart';
import 'package:tencent_trtc_cloud/trtc_cloud.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_def.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_listener.dart';
import 'package:tencent_trtc_cloud/tx_device_manager.dart';
import 'state.dart';

///@author:create by BZY
///Date: 2021/7/22 17:03
///Description:
class VideoLogic extends GetxController {
  TRTCCloud? _trtcCloud;
  TXDeviceManager? _deviceManager;
  VideoState state = VideoState();

  ///抛出需要的事件
  Function(dynamic)? onEvent;

  Timer? timer;

  @override
  void onInit() async {
    _trtcCloud = await TRTCCloud.sharedInstance();
    _trtcCloud!.setLogLevel(TRTCCloudDef.TRTC_LOG_LEVEL_NULL);
    state.userSign = Get.arguments ? ['userSign'];
    state.userId = Get.arguments ? ['userId'];
    state.roomId = Get.arguments ? ['roomId'];
    setVideoParams();
    startCount();
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    registerListener();
    if (state.roomId != null && state.roomId! > 0) {
      enterRoom();
    }
  }

  void registerListener() {
    _trtcCloud?.registerListener((type, params) {
      switch (type) {
        case TRTCCloudListener.onEnterRoom:

        ///进入房间成功
          if (params > 0) {
            state.hasEnterRoom = true;
            update(['localVideo']);
          } else {
            showToast('进入房间失败code:[$params]');
          }
          break;
        case TRTCCloudListener.onExitRoom:

        ///退出房间成功
          break;
        case TRTCCloudListener.onRemoteUserEnterRoom:
          log('onRemoteUserEnterRoom-----${state.roomId}---$type---$params');
        ///有用户进入房间 params userId 用户标识
        ///当有远端用户进入房间时,更改当前视频状态,同时开始重新计时
          state.remoteUserId = params;
          state.status = '接诊中...';
          state.countTime = 0;
          state.isUserEnter = true;
          update(['remoteVideo','statusView']);
          break;
        case TRTCCloudListener.onRemoteUserLeaveRoom:

        ///有用户退出房间,移除该用户的视频组件
        ///params{userId 用户标识,reason 离开原因，0表示用户主动退出房间，1表示用户超时退出，2表示被踢出房间。}
          state.remoteUserId = params['userId'];

          update(['remoteVideo']);
          break;
        case TRTCCloudListener.onUserVideoAvailable:
          log('onUserVideoAvailable-----${state.roomId}---$type---$params');
        ///有远端用户的可用视频流 params 为{userId 用户标识,available 画面是否开启}
        ///显示视频
          if (params['available']) {
            state.remoteUserId = params['userId'];
            state.status = '接诊中...';
            state.isUserEnter = true;
            update(['remoteVideo','statusView']);
          }
          break;
        case TRTCCloudListener.onUserAudioAvailable:

        ///有远端用户的可用音频流 params 为{userId 用户标识,available 声音是否开启}
        ///todo:声音开启的标识
          break;
        case TRTCCloudListener.onError:

        ///错误回调 params 为{errCode 错误码,errMsg 错误信息,extraInfo 扩展信息字段，个别错误码可能会带额外的信息帮助定位问题}
          log('onError---$params');
          break;
      }
    });
  }

  ///进入房间
  void enterRoom() async {
    await _trtcCloud?.enterRoom(
        TRTCParams(
            sdkAppId: Global.APP_ID,
            userId: state.userId ?? '', // 用户Id
            userSig: state.userSign ?? '', // 用户签名
            roomId: state.roomId ?? 0),
        TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL);
  }

  ///开启本地视频预览
  void startLocalPreview(viewId) {
    _trtcCloud?.startLocalPreview(true, viewId);
    _trtcCloud?.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
  }

  ///渲染远端视频流
  void startRemoteView(viewId) {
    _trtcCloud?.startRemoteView(state.remoteUserId ?? '', viewId,
        TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_SMALL);
  }

  Future<bool> muteAudio() async {
    state.isMute = !state.isMute;
    await _trtcCloud?.muteLocalAudio(state.isMute);
    return Future.value(state.isMute);
  }

  ///退出房间
  Future<void> exitRoom() async {
    await _trtcCloud?.exitRoom();
  }

  ///切换前后摄像头
  void switchCamera() {
    state.isFront = !state.isFront;
    _deviceManager?.switchCamera(state.isFront);
  }

  @override
  void onClose() {
    super.onClose();
    timer?.cancel();
    timer = null;
    exitRoom();
  }


  ///设置视频相关参数,目前采用640 × 360
  ///不使用美颜
  void setVideoParams() {
    _trtcCloud?.setVideoEncoderParam(TRTCVideoEncParam(
        videoResolution: TRTCCloudDef.TRTC_VIDEO_RESOLUTION_640_360,
        videoResolutionMode: TRTCCloudDef.TRTC_VIDEO_RESOLUTION_MODE_PORTRAIT));
    var manager = _trtcCloud?.getBeautyManager();
    if (manager != null) {
      manager
        ..setBeautyLevel(0)
        ..setBeautyStyle(1)
        ..setFilterStrength(0)
        ..setWhitenessLevel(0)
        ..setRuddyLevel(0);
    }

    _deviceManager = _trtcCloud?.getDeviceManager();
    _trtcCloud?.setVideoEncoderMirror(true);
  }

  ///开启一个计时器
  void startCount() {
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      state.countTime++;
      if (!state.isUserEnter && state.countTime >= 60) {
        ///如果超过一分钟患者还未进入房间,则医生端挂断视频
        onEvent?.call('noResponse');
      }
      updateTime();
    });
  }

  void updateTime() {
    int minutes = (state.countTime / 60).floor();
    int second = state.countTime % 60;
    state.showTime = '${getMinute(minutes)}:${getSecond(second)}';
    update(['countDown']);
  }

  String getMinute(int min) {
    if (min < 10) {
      return "0$min";
    } else {
      return min.toString();
    }
  }

  String getSecond(int min) {
    if (min < 10) {
      return "0$min";
    } else {
      return min.toString();
    }
  }
}
